#!/usr/bin/env python3
# -*- encoding: utf-8 -*-

'''
@file    :   pyqt_student_name_analysis.py
@date    :   2020-08-29 21:36:05
@author  :   huenrong
'''

import sys
import os.path
from ctypes import *
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMessageBox, QFileDialog
from ui_student_name_analysis import Ui_student_name_analysis
import time
import xlrd
from itertools import chain
from pypinyin import pinyin, Style
import difflib

# 学生名单路径
g_student_list_path = ''
# 待分析文件路径
g_analysis_file_path = ''

# 从学生名单获取到的学生姓名列表
g_full_student_names = []
# 从待分析文件夹获取到的学生姓名列表
g_analysis_student_names = []


class pyqt_student_name_analysis(QtWidgets.QWidget, Ui_student_name_analysis):
    """pyqt_rsu_psam_server_config pyqt 学生姓名分析软件界面类

    Args:
        QtWidgets (class): pyQt5.QtWidgets.QWidget类
        Ui_student_name_analysis (class):
            Ui_student_name_analysis.Ui_student_name_analysis
    """

    def __init__(self):
        """__init__ pyqt 界面类初始化
        """

        super(pyqt_student_name_analysis, self).__init__()
        # 初始化窗口
        self.setupUi(self)

        # 初始化信号和槽
        self.init_signal_slot()

    def init_signal_slot(self):
        """init_signal_slot 初始化信号和槽
        """

        # 选择学生名单按键
        self.student_list_push_button.clicked.connect(
            self.student_list_push_button_slot)

        # 选择文件夹按键
        self.file_path_push_button.clicked.connect(
            self.file_path_push_button_slot)

        # 开始分析按键
        self.start_push_button.clicked.connect(self.start_push_button_slot)

    def to_pinyin(self, s):
        """to_pinyin 转拼音

        Args:
            s (str/list): 待转换的字符串或列表

        Returns:
            str: 拼音字符串
        """

        return ''.join(chain.from_iterable(pinyin(s, style=Style.TONE3)))

    def file_name_listdir(self, file_path):
        """file_name_listdir 获取指定路径下的所有文件名列表(不包括扩展名, 包括文件夹)
                             已按照拼音排序

        Args:
            file_path (str): 文件夹路径

        Returns:
            [type]: 文件名列表
        """

        # 获取到的文件名, 不包括扩展名
        file_names = []

        for file in os.listdir(file_path):
            file_names.append(file.split(".", 1)[0])

        return sorted(file_names, key=self.to_pinyin)

    def student_list_push_button_slot(self):
        """student_list_push_button_slot 选择学生名单按键
        """

        student_list_path = QFileDialog.getOpenFileName()
        # 已选择文件
        if ('' != student_list_path[0]):
            # 将选择文件显示到文件框中
            self.student_list_line_edit.setText(student_list_path[0])

            global g_student_list_path
            global g_full_student_names

            # 获取文件名
            g_student_list_path = student_list_path[0]

            print("g_student_list_path: [%s]" % (g_student_list_path))

            # 分析名单, 获取学生姓名
            wb = xlrd.open_workbook(g_student_list_path)
            print(wb.sheet_names())
            sheet1 = wb.sheet_by_index(0)
            print("sheet1: ", sheet1)

            # 依次查找每一列的内容, 判断是否是姓名列
            # 暂时查找前100列
            for i in range(100):
                cols = sheet1.col_values(0)

                if ("姓名" == cols[0]):
                    g_full_student_names = cols[1:]
                    break

            # 姓名排序
            g_full_student_names = sorted(
                g_full_student_names, key=self.to_pinyin)

            print("g_full_student_names: ", g_full_student_names)

    def file_path_push_button_slot(self):
        """file_path_push_button_slot 选择文件夹按键
        """

        flie_path = QFileDialog.getExistingDirectory()
        # 已选择文件
        if ('' != flie_path):
            # 将选择文件显示到文件框中
            self.file_path_line_edit.setText(flie_path)

            global g_analysis_file_path

            # 获取文件路径
            g_analysis_file_path = flie_path

            print("g_analysis_file_path: [%s]" % (g_analysis_file_path))

    def start_push_button_slot(self):
        """start_push_button_slot 开始分析按键
        """

        global g_analysis_student_names

        if ('' == self.student_list_line_edit.text()):
            QMessageBox.critical(self, "错误", "请先选择学生名单")

            return

        if ('' == self.file_path_line_edit.text()):
            QMessageBox.critical(self, "错误", "请先选择待分析文件路径")

            return

        if ('' == self.left_num_line_edit.text()):
            QMessageBox.critical(self, "错误", "请先填入姓名前字符个数")

            return

        if ('' == self.right_num_line_edit.text()):
            QMessageBox.critical(self, "错误", "请先填入姓名后字符个数")

            return

        # 获取文件列表
        file_names = self.file_name_listdir(g_analysis_file_path)

        # 文件数量
        file_num = len(file_names)

        left_num = int(self.left_num_line_edit.text())
        right_num = int(self.right_num_line_edit.text())

        # 循环获取每个文件中的人名
        for i in range(file_num):
            name_len = len(file_names[i])
            g_analysis_student_names.append(
                file_names[i][left_num:(name_len - right_num)])

        print("g_analysis_student_names: ", g_analysis_student_names)

        # 所有学生姓名数量
        full_name_num = len(g_full_student_names)

        # 待分析学生姓名数量
        analysis_name_num = len(g_analysis_student_names)

        print("full_name_num: ", full_name_num)
        print("analysis_name_num: ", analysis_name_num)

        if (analysis_name_num > full_name_num):
            self.result_text_edit.append("注意: 待分析学生数量比实际学生数量多")
            self.result_text_edit.append(
                "注意: 实际学生数量: " + str(full_name_num))
            self.result_text_edit.append(
                "注意: 待分析学生数量: " + str(analysis_name_num))

        # 姓名匹配列表
        name_match_list = []
        # 姓名不匹配列表
        name_mismatch_list = []

        # 匹配名单计算, 显示
        name_match_list = set(g_full_student_names).intersection(
            set(g_analysis_student_names))

        name_match_list = sorted(
            name_match_list, key=self.to_pinyin)

        name_match_str = "匹配名单(" + str(len(name_match_list)) + "): " + \
            " ".join(name_match_list)
        self.result_text_edit.append(name_match_str)

        # 实际多余名单计算, 显示
        name_mismatch_list = set(g_full_student_names).difference(
            set(name_match_list))

        name_mismatch_list = sorted(
            name_mismatch_list, key=self.to_pinyin)

        name_mismatch_str = "实际多余名单(" + \
            str(len(name_mismatch_list)) + "): " + \
            " ".join(name_mismatch_list)
        self.result_text_edit.append(name_mismatch_str)

        # 待分析多余名单计算, 显示
        name_mismatch_list = set(g_analysis_student_names).difference(
            set(name_match_list))

        name_mismatch_list = sorted(
            name_mismatch_list, key=self.to_pinyin)

        name_mismatch_str = "待分析多余名单(" + \
            str(len(name_mismatch_list)) + "): " + \
            " ".join(name_mismatch_list)
        self.result_text_edit.append(name_mismatch_str)


if __name__ == '__main__':
    pass
